package com.liu.parse;


import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class CsdnCrawler extends AbstractCrawler {
    @Override
    protected String getBaseUrl(String url) {
        return url.contains("?") ? url.substring(0, url.indexOf("?")) : url;
    }

    @Override
    protected String createJekyllHeader(String title, String date, Elements tagsElements) {
        String jekyllTitle = "title: " + title + "\n";
        String jekyllDate = "date: " + date + "\n";
        String jekyllCategories = tagsElements.size() > 1 ? "categories:\n" + getTagsBoxValue(tagsElements, 1) : "";
        String jekyllTags = "tags:\n" + getTagsBoxValue(tagsElements, 0);
        return "---\nlayout: post\n" + jekyllTitle + jekyllDate + "author: 'zhangtao'\nheader-img: 'img/post-bg-2015.jpg'\ncatalog: false\n" + jekyllCategories + jekyllTags + "\n---\n";
    }

    private String getTagsBoxValue(Elements elements, int index) {
        Elements categoryElements = elements.get(index).select("a.tag-link");
        StringBuilder categories = new StringBuilder();
        for (Element categoryElement : categoryElements) {
            categories.append("- ").append(categoryElement.text().replace("\t", "").replace("\n", "").replace("\r", "")).append("\n");
        }
        return categories.toString();
    }
}